var gulp = require('gulp');
var sass=require('gulp-ruby-sass'),
     group=require('gulp-group-files'),
     replace = require('gulp-replace'),
    fileInclude= require('gulp-file-include'),
    cache= require('gulp-cache'),
    del = require('del'),
    browserSync= require('browser-sync');



//开发时=================================================================
//sass编译，
//指定输出到目录  css文件显示规则：nested,compact,expanded,compressed。
gulp.task('css',function(){

    //分组处理
    var sassFiles= {
        'css':{ src: 'res/sass/*.scss', out:'res/css'}
    };

    return group(sassFiles,function (key,fileset){
        return sass(fileset.src,{style:'expanded',noCache:true,compass:true})
            .on('error', function (err) {
                console.error('compile sass file error: %s', err.message);
            })
           // .pipe(replace('../../', '../'))
            .pipe(gulp.dest(fileset.out));
    })();

});


//html 处理，
//html块文件插入到html文件内
gulp.task('html-create', function() {
    gulp.src('pages/*.html')
        .pipe(fileInclude({
            prefix: '@@',
            basepath: '@root'
        }))
        .pipe(gulp.dest(''))
        .pipe(browserSync.stream());

});

//js库与插件处理
//复制js 库与插件源文件到指定位置；
gulp.task('lib',function(){
    var libs=[
        // jquery:
        {
            source:[
                'bower_components/jquery/dist/jquery.js',
                'bower_components/jquery/dist/README.md'
            ],
            out:"res/lib/jquery"
        },

        //jquery.browser
        {
            source:[
                'bower_components/jquery.browser/dist/jquery.browser.js',
                'bower_components/jquery.browser/BrowserDetect.js',
                'bower_components/jquery.browser/README.md'
            ],
            out:"res/lib/jquery/browser"
        }
    ];
    return libs.forEach(function(item){
        gulp.src(item.source).pipe(gulp.dest(item.out));
    });
});


//开启browserSync服务，实现浏览器自动刷新功能
gulp.task('browser-sync', function () {
    browserSync({
        files: "*.html,/res/css/*.css",
        server: {
            baseDir: "./"
        }
    });
});


//监控下列文件，文件变化时，先自动编译，然后再自动刷新浏览器显示结果；
gulp.task('watch', function() {
    gulp.watch('res/sass/**',['css']);
    gulp.watch('pages/**',['html-create']);
    gulp.watch('page-parts/**',['html-create']);
});


//开发时常用操作
gulp.task('dev', ['css','lib','html-create']);

//默认
gulp.task('default', ['dev'], function (){
    gulp.start(['watch', 'browser-sync']);
});










//发布时===================================================

//发布时的配置，项目名，版本号
var cfg={
    name:'release',
    ver:'1.0.0'
};
var src=cfg.name+"-"+cfg.ver;

//提取文件
gulp.task('release', function (){
    var paths=[
        // html
        { source: './*.html', out:src},

        //css files
        { source: 'res/css/*.*', out:src+"/res/css"},

        //lib files
        { source: 'res/lib/**/*.*', out:src+"/res/lib"},

        //js files
        { source: 'res/js/*.*', out:src+"/res/js"},

        //font files
        { source: 'res/font/**/*.*', out:src+"/res/font"},




        //background images
        {  source: 'res/images/bg/*.*', out:src+"/res/images/bg"},

        //background images single image
        { source: 'res/images/bg/single/*.*', out:src+"/res/images/bg/single"},

        //cont images
        { source: 'res/images/*.*',  out:src+"/res/images"},
        { source: 'res/images/cont/**/*.*',  out:src+"/res/images/cont"}

    ];

    return paths.forEach(function(item){
        gulp.src(item.source).pipe(gulp.dest(item.out));
    });

});

//提取page-parts文件，用于给后端使用
gulp.task('releasePiece', function (){
    var paths=[
        //html
        { source: 'page-parts/**/*.html', out:src+'/page-parts'}
    ];

    return paths.forEach(function(item){
        gulp.src(item.source).pipe(gulp.dest(item.out));
    });

});


//更新文件路径，即静态资源文件路径发生变化，可以使用此功能，配置所有css,js,html文件内的资源路径；
gulp.task('releasePath',['release-path-css','release-path-js','release-path-html']);
gulp.task('release-path-css',function(){
    //更新css内的资源路径。
    var cssFiles=src+'/res/css/*.css',
        sourcePath='/res/images',
        outPath='../images',
        cssFolder=src+'/res/css';
    return gulp.src(cssFiles)
        .pipe(replace(sourcePath, outPath))
        .pipe(gulp.dest(cssFolder));
});
gulp.task('release-path-js',function(){});
gulp.task('release-path-html',function(){
    //更html内图片的路径
    var htmlFiles=src+'/*.html',
        sourcePath='/res/',
        outPath='res/',
        htmlFolder=src;
    return gulp.src(htmlFiles)
        .pipe(replace(sourcePath, outPath))
        .pipe(gulp.dest(htmlFolder));
});


//clean 清理目录=====================================================
//全部清理
gulp.task('clean-all', ['clean-dev','clean-release','clean-cache'], function (){});

//清理开发时生成的文件
gulp.task('clean-dev', function(cb) {
    del([
        './*.html',
        'res/css',
        'res/**/*.css',
        'res/images/bg/*.png'
    ], cb)
});

//清理部署时生成的文件
gulp.task('clean-release',function (cb){
    del([src], cb)
});

//清理缓存
gulp.task('clean-cache', function (done) {
    return cache.clearAll(done);
});


